package com.healthcloud.controller;

import java.util.*;

import com.healthcloud.annotation.SysLog;
import com.healthcloud.entity.*;
import com.healthcloud.service.*;
import com.healthcloud.service.hospital.SysOrganiService;
import com.healthcloud.utils.*;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


/**
 * 医院信息表
 * 
 * @author yucl
 * @email yucailong1111@126.com
 * @date 2017-08-17 09:00:08
 */
@ApiIgnore
@Controller
@RequestMapping("hospital")
public class HlHospitalController {
	@Autowired
	private HlHospitalService hlHospitalService;

    @Autowired
    private DictService dictService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private LargeAreaService largeAreaService;

    @Autowired
    private AreaCodeService areaCodeService;

    @Autowired
    private SysOrganiService sysOrganiService;

    @Autowired
    private CommonMethod commonMethod;
	/**
	 * 列表
	 */
	@RequestMapping("/list")
	public String list(@RequestParam Map<String, Object> params){
		return "bus/hlhospital/hospitalmgr";
	}

    /**
     * 医院列表
     * @param bean
     * @param model
     * @param pageParam
     * @return
     */
	@RequiresPermissions("hlhospital:list")
	@RequestMapping(value = "/searchHlHospital")
	@ResponseBody
    public MsgVo searchHlHospital(HlHospitalEntity bean, Model model, @ModelAttribute("pageParam")PageParam pageParam){
        bean.setIds(hlHospitalService.getChildeIds());
        List<HlHospitalEntity> list = hlHospitalService.queryList(bean, pageParam);
        int count = hlHospitalService.queryTotal(bean);
        return new MsgVo(list,count,count,pageParam.getsEcho());
    }
	
	/**
	 * 新增页
	 */
	@RequestMapping("/tosave")
	@RequiresPermissions("hlhospital:save")
    public String toSave(Model model) {

        //大区列表数据
        List<LargeArea> largeAreaList = largeAreaService.findByEntityAll(new LargeArea());
        model.addAttribute("largeAreaList", largeAreaList);
        //科室列表
        Department department = new Department();
        department.setIsDel(false);
        department.setDepKind(DepartmentUtil.DEP_KIND_HOSP);
        List<Department> departmentList = departmentService.findByEntityAll(department);
        model.addAttribute("departmentList", departmentList);

        //机构设置
        List<SysOrganiEntity> organis = sysOrganiService.queryListAll();
        for(SysOrganiEntity organi : organis){
            organi.setOpen(true);
        }
        model.addAttribute("organis", organis);
        return "bus/hlhospital/addOrUpdatehospital";
    }
    
	/**
	 * 保存
	 */
    @SysLog("保存HlHospital")
    @RequestMapping("/save")
    @ResponseBody
    public ApiRes save(HlHospitalEntity entity, String[] depId, String[] showName) {
        //hlHospitalService.save(entity);
        List<HospitalDepartment> hdList = new ArrayList<>();
        if(depId!=null && showName!=null){
            if(depId.length!=showName.length){
                return new ApiRes(false,null,"depId.length!=showName.length", depId.length+"!="+showName.length);
            }
            for (int i =0; i<depId.length; i++){
                HospitalDepartment hd = new HospitalDepartment();
                hd.setDepId(Integer.valueOf(depId[i]));
                hd.setShowName(showName[i]);
                hdList.add(hd);
            }
        }
        hlHospitalService.save(entity, hdList);
        return ApiRes.SUCCESS;
    }
	
	/**
	 * 修改页
	 */	
	@RequestMapping("/toupdate")
    @RequiresPermissions("hlhospital:update")
    public String toUpdate(@Param("id") Long id, Model model) {

        HlHospitalEntity hospital = hlHospitalService.queryObject(id);
        model.addAttribute("entity", hospital);
        List<Dict> hospLvlList = dictService.findAllByType(DictUtils.HOSP_LVL); // 医院等级
        model.addAttribute("hospLvlList", hospLvlList);
        List<LargeArea> largeAreaList = largeAreaService.findByEntityAll(new LargeArea());//大区列表数据
        model.addAttribute("largeAreaList", largeAreaList);
        //根据areaCode获取各个等级的地区列表
        Map<String, List<AreaCode>> AreaCodeMap = areaCodeService.getAreaListAll(hospital.getAreaCode()==null?null:String. valueOf(hospital.getAreaCode()));
        List<AreaCode> provinceList = AreaCodeMap.get("1");//省列表
        List<AreaCode> cityList = AreaCodeMap.get("2");//市列表
        List<AreaCode> countyList = AreaCodeMap.get("3");//县列表
        List<AreaCode> townList = AreaCodeMap.get("4");//镇列表
        List<AreaCode> villageList = AreaCodeMap.get("5");//村列表
        model.addAttribute("provinceList", provinceList);
        model.addAttribute("cityList", cityList);
        model.addAttribute("countyList", countyList);
        model.addAttribute("townList", townList);
        model.addAttribute("villageList", villageList);
        //根据areaCode获取各个区code
        Long[] areaCodeArray = AreaCodeUtils.getCodeListAll(hospital.getAreaCode());
        model.addAttribute("provinceCode", areaCodeArray[0].toString());
        model.addAttribute("cityCode", areaCodeArray[1].toString());
        model.addAttribute("countyCode", areaCodeArray[2].toString());
        model.addAttribute("townCode", areaCodeArray[3].toString());
        model.addAttribute("villageCode", areaCodeArray[4].toString());
        //根据areaCode获取largeAreaCode
        String largeAreaCode = "";
        if(hospital.getAreaCode()!=null && hospital.getAreaCode().toString().length()>=2){
            AreaCode areaCode = new AreaCode();
            areaCode.setCode(Long.valueOf(hospital.getAreaCode().toString().substring(0,2)));
            List<AreaCode> areaCodeList = areaCodeService.findByEntityAll(areaCode);
            largeAreaCode = areaCodeList.get(0).getLargeAreaCode();
        }
        model.addAttribute("largeAreaCode", largeAreaCode);
        //科室列表
        Department department = new Department();
        department.setIsDel(false);
        department.setDepKind(DepartmentUtil.DEP_KIND_HOSP);
        List<Department> departmentList = departmentService.findByEntityAll(department);
        model.addAttribute("departmentList", departmentList);
        //科室信息
        List<HospitalDepartment> hdList = hlHospitalService.getHospitalDepartmentByHospId(hospital.getId());
        model.addAttribute("hdList", hdList);

        //机构列表
        List<SysOrganiEntity> organis = sysOrganiService.queryListAll();
        model.addAttribute("organis", organis);
        for(SysOrganiEntity organi : organis){
            organi.setOpen(true);
            if(organi.getId()==hospital.getOrganiId()){
                organi.setChecked(true);
            }
        }
        return "bus/hlhospital/addOrUpdatehospital";
    }
	
    /**
     * 修改
     */
    @SysLog("修改HlHospital")
    @RequestMapping("/update")
    @ResponseBody
    public ApiRes update(HlHospitalEntity entity, String[] depId, String[] showName) {
        List<HospitalDepartment> hdList = new ArrayList<>();
        if(depId!=null && showName!=null) {
            if (depId.length != showName.length) {
                return new ApiRes(false, null, "depId.length!=showName.length", depId.length + "!=" + showName.length);
            }
            for (int i = 0; i < depId.length; i++) {
                HospitalDepartment hd = new HospitalDepartment();
                hd.setDepId(Integer.valueOf(depId[i]));
                hd.setShowName(showName[i]);
                hdList.add(hd);
            }
        }
        hlHospitalService.update(entity, hdList);
        return ApiRes.SUCCESS;
    }

	
    /**
     * 删除
     */
    @SysLog("删除HlHospital")
    @RequestMapping("/delete")
    @RequiresPermissions("hohospital:delete")
    @ResponseBody
    public ApiRes delete(Long[] ids) {
        hlHospitalService.logicalDeletes(ids);
        return ApiRes.SUCCESS;
    }

    /**
     * 获取医院列表
     * @return
     */
    @RequestMapping(value = "/selectHospital")
    public @ResponseBody
    ApiRes selectHospital(HlHospitalEntity bean, @ModelAttribute("pageParam")PageParam pageParam){

        List<HlHospitalEntity> list = hlHospitalService.queryList(bean, pageParam);
        int total = hlHospitalService.queryTotal(bean);
        return new ApiRes(true,list,null,String.valueOf(total));
    }

    /**
     * 根据医院id查询 医院与科室关联信息列表（所含科室，科室别名。。。）
     * @param id 医院id
     * */
    @RequestMapping(value = "/getHospitalDepartmentByHospId", method = RequestMethod.POST)
    public @ResponseBody
    ApiRes getHospitalDepartmentByHospId(Long id){
        //科室信息
        List<HospitalDepartment> hdList = hlHospitalService.getHospitalDepartmentByHospId(id);
        return new ApiRes(true,hdList,null,null);
    }


    /**
     * ajax验证医院是否存在
     *
     *  */
    @RequestMapping(value = "/validateHospName")
    public @ResponseBody Object validateHospName(String hospName, String exception){
        Map<String,Boolean> map = new HashMap<>();
        if(hospName!=null && exception!=null && hospName.trim().equals(exception.trim())){
            map.put("valid",true);
            return map;
        }
        if(hospName==null||"".equals(hospName.trim())){
            map.put("valid",false);
            return map;
        }
        HlHospitalEntity entity = hlHospitalService.queryByHospName(hospName);
        if (entity==null) {
            map.put("valid",true);
            return map;
        } else {
            map.put("valid",false);
            return map;
        }
    }

    @RequestMapping(value = "/getHospitalList", method = RequestMethod.POST)
    public @ResponseBody List<HlHospitalEntity> getHospitalList(String areaCode){

        List<HlHospitalEntity> list = hlHospitalService.getHospitalListByAreaCode(areaCode, null, hlHospitalService.getChildeIds());
        return list;
    }

}
